package com.bao.interkont.controller;

import com.bao.interkont.pojo.Result;
import com.bao.interkont.pojo.User;
import com.bao.interkont.server.UserServer;
import com.bao.interkont.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author bao*
 * @version 1.0
 */
@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserServer userServer;

    // 获取全部用户
    @GetMapping("/users")
    public Result getUser() {
        log.info("获取用户列表");
        List<User> users = userServer.getUser();
        return Result.success(users);
    }

    @GetMapping("/users/uid/{uid}")
    public Result getUserByUid(@PathVariable Integer uid) {
        log.info("获取用户通过uid");
        User user = userServer.getUserByUid(uid);
        return Result.success(user);
    }

    //用于注册时检测是否有相同的账号
    @GetMapping("/users/account")
    public Result isAccountSame(String account) {
        User user = userServer.isAccountSame(account);
        if(user==null) {
            return Result.success();
        }else
            return Result.error("账号已被注册");
    }

    // 添加注册用户
    @PostMapping("/users")
    public Result addUser(@RequestBody User user) {
        log.info("{}",user);
        System.out.println(user);
        userServer.addUser(user);
        return Result.success();
    }

    // 前端通过token来获取登录用户信息
    @GetMapping("/users/{token}")
    public Result getUserByToken(@PathVariable String token) {
        try{
            Claims claims = JwtUtils.parseJWT(token);
            return Result.success(claims);
        }catch (Exception e){
            return Result.error("未登录");
        }
    }
}
